package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Patterns;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.BaseInfoBean;
import com.zlx.module_base.base_api.res_data.HomeSearchBean;
import com.zlx.module_base.base_api.res_data.PurchaseVideoBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.NullTokenUtils;
import com.zlx.sharelive.utils.StringUt;

import org.jetbrains.annotations.NotNull;

import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.bzcoder.mediapicker.cameralibrary.util.ScreenUtils;

/**
 * 搜索结果页面
 */
public class HomeSearchListAc extends BaseAc {

    @BindView(R.id.rv_data1)
    RecyclerView rv_data1;
    @BindView(R.id.rv_data2)
    RecyclerView rv_data2;
    @BindView(R.id.rv_data3)
    RecyclerView rv_data3;
    @BindView(R.id.et_search)
    EditText et_search;

    private int page = 1;
    private String text;
    private String over;
    private int videoCount;
    private BaseInfoBean mBaseInfoBean;
    private HomeSearchBean.InfoDTO mData;
    private final List<HomeSearchBean.InfoDTO.LongVideoDTO> mList1 = new ArrayList<>();
    private CommonRecyclerViewAdapter<HomeSearchBean.InfoDTO.LongVideoDTO> mAdapter1;
    private final List<HomeSearchBean.InfoDTO.ShortVideoDTO> mList2 = new ArrayList<>();
    private CommonRecyclerViewAdapter<HomeSearchBean.InfoDTO.ShortVideoDTO> mAdapter2;
    private final List<HomeSearchBean.InfoDTO.ArticleDTO> mList3 = new ArrayList<>();
    private CommonRecyclerViewAdapter<HomeSearchBean.InfoDTO.ArticleDTO> mAdapter3;
    private final List<String> mImageList = new ArrayList<>();
    private CommonRecyclerViewAdapter<String> mImageAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.item_home_search_list;
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mAdapter1.notifyItemChanged(msg.arg1);
                    break;
            }
        }
    };

    @Override
    public void initViews() {
        super.initViews();

        text = getIntent().getStringExtra("text");
        mData = (HomeSearchBean.InfoDTO) getIntent().getSerializableExtra("data");
        et_search.setText(text);

        getBaseInfo();
        initEditText();
        queryById();
        initRecyclerView1();
        initRecyclerView2();
        initRecyclerView3();

        setData();
    }

    private void initRecyclerView3() {
        rv_data3.setLayoutManager(new LinearLayoutManager(HomeSearchListAc.this));

        mAdapter3 = new CommonRecyclerViewAdapter<HomeSearchBean.InfoDTO.ArticleDTO>(HomeSearchListAc.this, mList3) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, HomeSearchBean.InfoDTO.ArticleDTO entity, int position) {
                ImageView iv_community_head = holder.getView(R.id.iv_community_head);

                GlideImgManager.glideLoader(HomeSearchListAc.this, entity.getAvatars(), iv_community_head, 0);

                holder.setText(R.id.tv_community_nickname, entity.getNickname());

                ImageView tv_yin = holder.getView(R.id.tv_yin);//阴影 判断是否是收费的

                if (!StringUt.isEmpty(entity.getIzFee())) {
                    if (entity.getIzFee().equals("1")) {
                        tv_yin.setVisibility(View.VISIBLE);
                        ((ImageView) holder.getView(R.id.iv_reward_img)).setVisibility(View.VISIBLE);
                    } else {
                        tv_yin.setVisibility(View.GONE);
                        ((ImageView) holder.getView(R.id.iv_reward_img)).setVisibility(View.GONE);
                    }
                } else {
                    tv_yin.setVisibility(View.GONE);
                }

                ImageView iv_community_vip = holder.getView(R.id.iv_community_vip);
                ImageView iv_community_goddess = holder.getView(R.id.iv_community_goddess);

                holder.setText(R.id.tv_reward_number, entity.getReword());
                if (!StringUt.isEmpty(entity.getIsvip())) {
                    if (entity.getIsvip().equals("1")) {
                        iv_community_vip.setVisibility(View.GONE);
                    } else {
                        iv_community_vip.setVisibility(View.VISIBLE);
                    }
                }

                if (!StringUt.isEmpty(entity.getAuthentication())) {
                    if (entity.getAuthentication().equals("2")) {
                        iv_community_goddess.setVisibility(View.GONE);
                    } else {
                        iv_community_goddess.setVisibility(View.VISIBLE);
                    }
                }
                if (!StringUt.isEmpty(entity.getIsDz())) {
                    if (entity.getIsDz().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_fabulous_img)).setImageResource(R.mipmap.fabulous_img_true);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_fabulous_img)).setImageResource(R.mipmap.fabulous_img2);
                    }
                }

                holder.setText(R.id.tv_community_address, entity.getCity());
                holder.setText(R.id.tv_community_text_title, entity.getTitle());
                holder.setText(R.id.tv_community_text_content, entity.getText());
                holder.setText(R.id.tv_share_number, entity.getShares());
                holder.setText(R.id.tv_fabulous_number, entity.getLikes());
                holder.setText(R.id.tv_comment_number, entity.getComments());

                holder.setText(R.id.tv_community_time, entity.getCreateTime());

                List<String> mImageList = new ArrayList<>();
                if (!StringUt.isEmpty(entity.getThumb())) {
                    mImageList.add(entity.getThumb());
                }
                if (!StringUt.isEmpty(entity.getThumb2())) {
                    mImageList.add(entity.getThumb2());
                }
                if (!StringUt.isEmpty(entity.getThumb3())) {
                    mImageList.add(entity.getThumb3());
                }
                if (!StringUt.isEmpty(entity.getThumb4())) {
                    mImageList.add(entity.getThumb4());
                }
                if (!StringUt.isEmpty(entity.getThumb5())) {
                    mImageList.add(entity.getThumb5());
                }
                if (!StringUt.isEmpty(entity.getThumb6())) {
                    mImageList.add(entity.getThumb6());
                }
                if (!StringUt.isEmpty(entity.getThumb7())) {
                    mImageList.add(entity.getThumb7());
                }
                if (!StringUt.isEmpty(entity.getThumb8())) {
                    mImageList.add(entity.getThumb8());
                }
                if (!StringUt.isEmpty(entity.getThumb9())) {
                    mImageList.add(entity.getThumb9());
                }

                RecyclerView rv_community_image = holder.getView(R.id.rv_community_image);

                rv_community_image.setLayoutManager(new GridLayoutManager(HomeSearchListAc.this, 4));

                CommonRecyclerViewAdapter<String> mImageAdapter = new CommonRecyclerViewAdapter<String>(HomeSearchListAc.this, mImageList) {
                    @Override
                    public void convert(CommonRecyclerViewHolder holder, String entity, int position1) {
                        FrameLayout fl_yin = holder.getView(R.id.fl_yin);

                        if (!StringUt.isEmpty(mList3.get(position).getIzFee())) {
                            if (mList3.get(position).getIzFee().equals("1")) {
                                fl_yin.setVisibility(View.VISIBLE);
                            } else {
                                fl_yin.setVisibility(View.GONE);
                            }
                        } else {
                            fl_yin.setVisibility(View.GONE);
                        }

                        ImageView iv_community_image = holder.getView(R.id.iv_community_image);

                        GlideImgManager.glideLoader(HomeSearchListAc.this, entity, iv_community_image, 1);
                    }

                    @Override
                    public int getLayoutViewId(int viewType) {
                        return R.layout.item_community_image_layout;
                    }
                };
                rv_community_image.setAdapter(mImageAdapter);
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_community_type2;
            }
        };

        rv_data3.setAdapter(mAdapter3);

        mAdapter3.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                startActivity(new Intent(HomeSearchListAc.this, CommunityDetailsAc.class)
                        .putExtra("id", mList3.get(position).getId()));
            }
        });
    }

    private void initRecyclerView2() {
        rv_data2.setLayoutManager(new GridLayoutManager(this, 2));

        mAdapter2 = new CommonRecyclerViewAdapter<HomeSearchBean.InfoDTO.ShortVideoDTO>(this, mList2) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, HomeSearchBean.InfoDTO.ShortVideoDTO entity, int position) {
                GlideImgManager.glideLoader(HomeSearchListAc.this, entity.getVideo(), holder.getView(R.id.iv_short_video_image), 1);
                holder.setText(R.id.tv_like_count, entity.getLikeCount());
                if (entity.getIsLike().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_like_count)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_like_count)).setImageResource(R.mipmap.fabulous_img_false);
                }
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_short_video;
            }
        };

        rv_data2.setAdapter(mAdapter2);

        mAdapter2.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                //先判断是否登录
                if (null != SPUtil.getObjectFromShare(HomeSearchListAc.this,
                        Constants.USERINFO)) {
                    //免费还有次数
                    if (videoCount > 0) {
                        startActivity(new Intent(HomeSearchListAc.this,
                                ShortVideoDetailsAc.class)
                                .putExtra("id", mList2.get(position).getId())
                                .putExtra("video", mList2.get(position).getVideo()));
                    } else {
                        //没有免费次数 弹出充值会员
                        dialogMember();
                    }
                } else {
                    startActivity(new Intent(HomeSearchListAc.this, LoginAc.class));
                }
            }
        });
    }

    /**
     * 用户基本信息
     */
    private void getBaseInfo() {
        ApiUtil.getUserApi().getBaseInfo(SPUtil.getToken(this)).
                observe(this, new BaseObserver<>(
                        new BaseObserverCallBack<ApiResponse<BaseInfoBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseInfoBean> data) {
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (data.getData().getCode() == 0) {
                                            if (null != data.getData().getInfo()) {
                                                mBaseInfoBean = data.getData();
                                            }
                                        } else {
                                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();

                            }
                        }));
    }

    private void initEditText() {
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return actionId == EditorInfo.IME_ACTION_SEND
                        || (event != null && event.getKeyCode() ==
                        KeyEvent.KEYCODE_ENTER);
            }
        });

        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(HomeSearchListAc.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (StringUt.isEmpty(et_search.getText().toString().trim())) {
                        Toast.makeText(HomeSearchListAc.this, "搜索内容不可为空", Toast.LENGTH_SHORT).show();
                    } else {
                        homeSearch();
                    }
                }
                return false;
            }
        });
    }

    private void setData() {
        mList1.clear();
        if (null != mData) {
            if (null != mData.getLongVideo()) {
                mList1.addAll(mData.getLongVideo());
                mAdapter1.notifyDataSetChanged();
            }
        }

        for (int i = 0; i < mList1.size(); i++) {
            final String video = mList1.get(i).getVideo();
            final int position = i;
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    if (!StringUt.isEmpty(video)) {
                        if (isValid(video) == true) {
                            if (!StringUt.isEmpty(getPlayTime(video))) {
                                String time = getFormatedDateTime("mm:ss", Long.valueOf(getPlayTime(video)));
                                mList1.get(position).setPeriod(time);
                                Message msg = new Message();
                                msg.what = 1;
                                msg.arg1 = position;
                                handler.sendMessage(msg);
                            }
                        }
                    }
                }
            }.start();
        }

        mList2.clear();
        if (null != mData) {
            if (null != mData.getShortVideo()) {
                mList2.addAll(mData.getShortVideo());
                mAdapter2.notifyDataSetChanged();
            }
        }
        mList3.clear();
        if (null != mData) {
            if (null != mData.getArticle()) {
                mList3.addAll(mData.getArticle());
                mAdapter3.notifyDataSetChanged();
            }
        }
    }


    private void homeSearch() {
        ApiUtil.getHomeApi().homeSearch(String.valueOf(page),
                et_search.getText().toString().trim()).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<HomeSearchBean>>() {
            @Override
            public void onSuccess(ApiResponse<HomeSearchBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    mData = data.getData().getInfo().get(0);
                                    setData();
                                    if (data.getData().getInfo().get(0).getLongVideo().size() > 0 ||
                                            data.getData().getInfo().get(0).getShortVideo().size() > 0 ||
                                            data.getData().getInfo().get(0).getArticle().size() > 0) {
                                    } else {
                                        Toast.makeText(HomeSearchListAc.this, "没有搜索出结果", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(HomeSearchListAc.this, "没有搜索出结果", Toast.LENGTH_SHORT).show();
                                }
                            }
                        } else {
                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 根据用户id查询个人信息
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(this), (String) SPUtil.get(this, Constants.SP_ID, ""))
                .observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (data.getData().getCode() == 0) {
                                    if (null != data.getData().getInfo()) {
                                        if (data.getData().getInfo().size() > 0) {
                                            if (null != data.getData().getInfo().get(0).getResult()) {
                                                if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getVideoCount())) {
                                                    videoCount = Integer.valueOf(data.getData().getInfo().get(0).getResult().getVideoCount());
                                                    if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                        over = data.getData().getInfo().get(0).getResult().getMoney();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    /**
     * 长视频
     */
    private void initRecyclerView1() {
        rv_data1.setLayoutManager(new LinearLayoutManager(this));

        mAdapter1 = new CommonRecyclerViewAdapter<HomeSearchBean.InfoDTO.LongVideoDTO>(this, mList1) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, HomeSearchBean.InfoDTO.LongVideoDTO entity, int position) {

                GlideImgManager.glideLoader(HomeSearchListAc.this, entity.getCover(), holder.getView(R.id.iv_recommend), 1);

                GlideImgManager.glideLoader(HomeSearchListAc.this, entity.getAvatar(), holder.getView(R.id.iv_recommend_head), 0);

                holder.setText(R.id.tv_recommend_title, entity.getTitle());

                holder.setText(R.id.tv_recommend_nickname, entity.getNickname());

                holder.setText(R.id.tv_time, entity.getPeriod());

                if (!StringUt.isEmpty(entity.getIsLike())) {
                    if (entity.getIsLike().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img_true);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img2);
                    }
                } else {
                    ((ImageView) holder.getView(R.id.iv_fabulous)).setImageResource(R.mipmap.fabulous_img2);
                }

                if (entity.getIsVip().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.VISIBLE);
                } else {
                    ((ImageView) holder.getView(R.id.iv_vip)).setVisibility(View.GONE);
                }
                if (!StringUt.isEmpty(entity.getAuthentication())) {
                    if (entity.getAuthentication().equals("1")) {
                        ((ImageView) holder.getView(R.id.iv_goddess)).setVisibility(View.VISIBLE);
                    } else {
                        ((ImageView) holder.getView(R.id.iv_goddess)).setVisibility(View.GONE);
                    }
                }
                holder.setText(R.id.tv_pageViews, entity.getPageViews());
                holder.setText(R.id.tv_fabulous, entity.getLikeCount());
                holder.setText(R.id.tv_comment_count, entity.getCommentCount());
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_long_video;
            }
        };

        rv_data1.setAdapter(mAdapter1);

        mAdapter1.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (mList1.get(position).getIsMe().equals("1")) {
                    startActivity(new Intent(HomeSearchListAc.this, VideoDetailsAc.class)
                            .putExtra("id", mList1.get(position).getId())
                            .putExtra("title", mList1.get(position).getTitle()));
                } else {
                    if (mList1.get(position).getIsPaid().equals("1")) {
                        //免费还有次数
                        if (videoCount > 0) {
                            dialogFreePlay(mList1.get(position).getId()
                                    , mList1.get(position).getTitle());
                        } else {
                            //没有免费次数
                            dialogMember();
                        }
                    } else {
                        //收费
                        if (!StringUt.isEmpty(mList1.get(position).getIsFlag())) {
                            if (mList1.get(position).getIsFlag().equals("0")) {
                                //未购买 弹出购买窗口
                                dialogPay(
                                        mList1.get(position).getId(),
                                        mList1.get(position).getMoney());
                            } else {//已购买
                                startActivity(new Intent(HomeSearchListAc.this, VideoDetailsAc.class)
                                        .putExtra("id", mList1.get(position).getId())
                                        .putExtra("title", mList1.get(position).getTitle()));
                            }
                        } else {
                            startActivity(new Intent(HomeSearchListAc.this, VideoDetailsAc.class)
                                    .putExtra("id", mList1.get(position).getId())
                                    .putExtra("title", mList1.get(position).getTitle()));
                        }
                    }
                }
            }
        });
    }

    private void dialogMember() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_home_member, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        Button bt_member = view.findViewById(R.id.bt_member);

        bt_member.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomeSearchListAc.this, MemberAc.class)
                        .putExtra("data", mBaseInfoBean));
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 弹出观看视频友情提示
     */
    private void dialogFreePlay(String id, String title) {
//1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_home_play, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(videoCount + "");

        RelativeLayout rl_close = view.findViewById(R.id.rl_close);

        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        RelativeLayout ll_dialog_play = view.findViewById(R.id.ll_dialog_play);

        ll_dialog_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HomeSearchListAc.this, VideoDetailsAc.class)
                        .putExtra("id", id)
                        .putExtra("title", title));
                dialog.dismiss();
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 购买
     */
    private void dialogPay(String id, String money) {
//1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_play_video, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        tv_money.setText("￥" + money);

        TextView tv_over = view.findViewById(R.id.tv_over);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        if (StringUt.isEmpty(over)) {
            tv_over.setText("￥0");
        } else {
            tv_over.setText("￥" + over);
        }

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(money) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(money)) {
                        //钱够支付
                        purchaseVideo(id, money);
                        dialog.dismiss();
                    } else {
                        Toast.makeText(HomeSearchListAc.this, "余额不足", Toast.LENGTH_SHORT).show();
                    }
                } else if (StringUt.isEmpty(over)) {
                    Toast.makeText(HomeSearchListAc.this, "余额不足", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 余额购买视频
     *
     * @param id
     * @param money
     */
    private void purchaseVideo(String id, String money) {
        dialogPass(id, money);
    }

    /**
     * 支付密码
     */
    private void dialogPass(String id, String money) {
        PurchaseVideoBean purchaseVideoBean = new PurchaseVideoBean();
        purchaseVideoBean.setId(id);
        purchaseVideoBean.setMoney(money);

        final PayPassDialog dialog = new PayPassDialog(this);
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        //6位输入完成回调
                        Log.d("ret", "joker  输入的密码===" + passContent);
                        purchaseVideoBean.setPayPassWord(passContent);

                        ApiUtil.getVideoApi().purchaseVideo(SPUtil.getToken(HomeSearchListAc.this),
                                purchaseVideoBean).observe(HomeSearchListAc.this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseBean> data) {
                                if (null != data) {
                                    if (null != data.getData()) {
                                        if (data.getData().getCode() == 0) {
                                            Toast.makeText(HomeSearchListAc.this, "购买成功", Toast.LENGTH_SHORT).show();
                                            dialog.dismiss();
                                            page = 1;
                                            homeSearch();
                                            queryById();
                                        } else {
                                            NullTokenUtils.isNullToken(data.getData().getCode(), data.getData().getMsg());
                                        }
                                    }
                                }
                            }
                        }));
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

    @OnClick({R.id.tv_back, R.id.iv_remove})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.iv_remove:
                et_search.setText("");
                break;
        }
    }

    //改变bitmap尺寸的方法
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }


    private String getPlayTime(String mUri) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String duration = "";
        try {
            if (mUri != null) {
                HashMap headers = null;
                if (headers == null) {
                    headers = new HashMap();
                    headers.put("User-Agent", "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1");
                }
                mmr.setDataSource(mUri, headers);
            } else {
                //mmr.setDataSource(mFD, mOffset, mLength);
            }
            //注意地址 mUri= /storage/emulated/0/youshixiu/rectools/录屏专家190629113518.mp4    本地
            duration = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_DURATION);//时长(毫秒)
            String width = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);//宽
            String height = mmr.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);//高
        } catch (Exception ex) {
            Log.e("TAG", "MediaMetadataRetriever exception " + ex);
        } finally {
            mmr.release();
        }
        return duration;
    }

    public static String getFormatedDateTime(String pattern, long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(new Date(dateTime + 0));
    }


    private boolean isValid(String urlString) {
        try {
            URL url = new URL(urlString);
            return URLUtil.isValidUrl(urlString) && Patterns.WEB_URL.matcher(urlString).matches();
        } catch (MalformedURLException e) {

        }
        return false;
    }
}
